package com.gitee.neuray.security.gateway.config;

import com.gitee.neuray.security.auth.client.config.UserAuthConfig;
import com.gitee.neuray.security.auth.client.jwt.UserAuthUtil;
import com.gitee.neuray.security.auth.common.util.jwt.IJWTInfo;
import com.gitee.neuray.security.common.context.BaseContextHandler;
import com.netflix.zuul.context.RequestContext;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @author: zhhongyu
 * @description:
 * @since: Create in 11:12 2020/3/27
 */
@Component
public class ZuuljwtUser {
    @Autowired
    private UserAuthConfig userAuthConfig;
    @Autowired
    private UserAuthUtil userAuthUtil;

    /**
     * 返回token中的用户信息
     *
     * @param request
     * @param ctx
     * @return
     */
    public IJWTInfo getJWTUser(HttpServletRequest request, RequestContext ctx) throws Exception {
        String authToken = request.getHeader(userAuthConfig.getTokenHeader());
        if (StringUtils.isBlank(authToken)) {
            authToken = request.getParameter("token");
        }
        ctx.addZuulRequestHeader(userAuthConfig.getTokenHeader(), authToken);
        BaseContextHandler.setToken(authToken);
        return userAuthUtil.getInfoFromToken(authToken);
    }
}
